package com.bsoft.config;

import com.bsoft.message.Demo05Message;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.batch.BatchingStrategy;
import org.springframework.amqp.rabbit.batch.SimpleBatchingStrategy;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.BatchingRabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;

@Configuration
public class RabbitConfig {
    /**
     * Direct exchange
     */
    public static class DirectExchangeDemoConfiguration {
        //创建bena
        @Bean
        public Queue demo05Queue() {
            return new Queue(Demo05Message.QUEUE, //queue名字
                    true,  //是否持久化
                    false, //是否排它
                    false); //是否自动删除
        }

        //创建Direct Exchange
        //Direct Exchange
        @Bean
        public DirectExchange demo05Exchange() {
            return new DirectExchange(Demo05Message.EXCHANGE,
                    true, //是否持久化
                    false);  //是否排它
        }

        //创建Binding
        @Bean
        public Binding demo05Bingding() {
            return BindingBuilder.bind(demo05Queue()).to(demo05Exchange()).with(Demo05Message.ROUTING_KEY);
        }

        @Bean
        public BatchingRabbitTemplate batchingRabbitTemplate(ConnectionFactory connectionFactory) {
            // 创建 BatchingStrategy 对象，代表批量策略
            int batchSize = 16384; //超过收集的消息数量的最大条数
            int bufferLimit = 33554432;//每次批量发送消息的最大内存
            int timeout = 3000;// 超过收集的时间的最大等待时长 单位毫秒
            BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(batchSize, bufferLimit, timeout);
            //创建TaskScheduler 对象 用于实现超时发送的定时器
            TaskScheduler taskScheduler = new ConcurrentTaskScheduler();
            //创建BatchingRabbitTemplate 对象
            BatchingRabbitTemplate batchingRabbitTemplate = new BatchingRabbitTemplate(batchingStrategy, taskScheduler);
            batchingRabbitTemplate.setConnectionFactory(connectionFactory);
            return batchingRabbitTemplate;

        }

    }

}
